package cn.myweixin.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cn.myweixin.util.WeixinUtil;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class callback
 * 可删除
 */
@WebServlet("/callback")
public class callbackServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String  APPID="wx1341463c2dca02ba";
	private static final String  APPSECRET="7679103275a4ac992a3a834655ea2c90";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public callbackServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String code=request.getParameter("code");
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APPID
				+ "&secret="+APPSECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		JSONObject jsonObject=WeixinUtil.doGetStr(url);
		String openid=jsonObject.getString("openid");
		String access_token=jsonObject.getString("access_token");
		
		String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
				+ "&openid="+openid
				+ "&lang=zh_CN";
		JSONObject userIn=WeixinUtil.doGetStr(infoUrl);
		String nickname=userIn.getString("nickname");
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		//response.getWriter().println(userIn);
		request.setAttribute("openid", openid);
		request.setAttribute("code", access_token);
		request.getRequestDispatcher("/index.jsp").forward(request, response);
		//response.getWriter().println("用户账号："+openid+"\n用户昵称："+nickname);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
